|
|
|
|
|
|
|
The Ten Commandments for Safe API Programming (Revised Yet Again) |
|
|
|
|
|
|
|
|
I wrote the original "Ten Commandments for Safe API Programming" around 1992, and versions of it have appeared in publications, conference proceedings, Web sites, and books. I've stated that following these commandments can solve almost every API programming problem, and for some reason people seem reluctant to believe me. Perhaps I'll be able to make my point with this book, because many of the puzzles include hints that refer to the relevant commandment. |
|
|
|
|
|
|
|
|
Don't worry if some (or all) of the concepts in these commandments are unclear right now. By the time you work your way through the puzzles, solutions, and tutorials, they will become second nature. |
|
|
|
|
|
|
|
|
I
Remember ByVal and keep it wholly. |
|
|
|
|
|
|
|
|
Correct use of the ByVal statement is the single most important factor for successful API programming from Visual Basic. Keep in mind that the ByVal keyword is sometimes used in the function call itself, not just in the declaration. For applying advanced techniques, it is essential to really understand what the ByVal keyword does and its impact on how API functions are called from Visual Basic. |
|
|
|
|
|
|
|
|
II
Thou shalt check thy parameter types. |
|
|
|
|
|
|
|
|
Getting parameter types correct is critical, more so under Win32 than it was under Win 16. Under Win32, most parameters are passed as 32-bit values regardless of their actual size. Thus the traditional "bad DLL calling convention" error does not detect as many errors as it did under Win 6. The result can be subtle bugs that are data-dependent and extremely difficult to track down. Keep in mind that many API functions can accept more than one data type for a given parameter, so it's important to understand exactly how different parameter types are passed to the functions. Also remember that Visual Basic practices a form of evil type coercion in which it will automatically convert values from one type to another without warning. This can lead to passing a parameter that you think is the correct type, but that actually contains an invalid value. |
|
|
|
|
|
|
|
|
III
Thou shalt check thy return types. |
|
|
|
|
|
|
|
|
Most API functions return 32-bit long results. Problems with return values usually occur when your declaration returns anything other than a Long value. The most common mistake is to forget to add a return type to the function declaration. In this case, Visual Basic defaults to a variant return type, which is sure to be incorrect and will typically cause either a "bad DLL calling convention" error or a memory exception. |
|
|
|
|
|